import React, {useRef, useState} from 'react';
import ProTable from '@ant-design/pro-table';
import {Button, Switch, message, Space, Popconfirm, Avatar} from 'antd';
import {PageContainer} from '@ant-design/pro-layout';
import {PlusOutlined, FundViewOutlined, DeleteOutlined} from '@ant-design/icons';
import {delContent, contentList, isHot, isTop, isHideContent, isRec} from '@/services/cms';
import Edit from './components/Edit';
import Recycle from './components/Recycle';

const Index = () => {
  const [isModalVisible, setIsModalVisible] = useState(false); // 编辑弹窗
  const [isModalRecycle, setIsModalRecycle] = useState(false); // 弹窗
  const [editId, setEditId] = useState(undefined);
  const [lockId, setLockId] = useState('');

  const actionRef = useRef();

  /**
   * 获取数据
   * 作者：糜家智
   * 时间：2021/8/2 18:03
   */
  const getData = async (params) => {
    const res = await contentList(params);
    return {
      data: res.data.list,
      success: true,
      total: res.data.count,
    };
  };

  /**
   * 模态框的显示和隐藏
   */
  const isShowModal = async (show, content_id = null) => {
    setEditId(content_id);
    setIsModalVisible(show);
  };

  const isShowRecycleModal = async (show) => {
    setIsModalRecycle(show);
  };

  /**
   * 删除列
   * @param id
   * @returns {Promise<void>}
   */
  const handleOk = async (data) => {
    let arr = {};
    arr['content'] = [];
    arr['content'][0] = data;
    const res = await delContent(arr);
    if (res.code === 200) {
      actionRef.current.reload();
      message.success(res.msg);
    }
  };

  const handleIsContent = async (data, id, type) => {
    setLockId(data.content_id + type);

    const setId = id === 0 ? 1 : 0;
    const arr = [];
    arr[0] = data;
    let res = {};

    switch (type) {
      case 'top':
        res = await isTop({content: arr, is_top: setId});
        break;
      case 'hot':
        res = await isHot({content: arr, is_hot: setId});
        break;
      case 'rec':
        res = await isRec({content: arr, is_rec: setId});
        break;
      case 'hide':
        res = await isHideContent({content: arr, is_hide: setId});
        break;
      default:
    }

    if (res.code === 200) {
      message.success(res.msg);
    }
    setLockId('');
  };

  const columns = [
    {
      title: 'ID',
      dataIndex: 'content_id',
      key: 'content_id',
      hideInSearch: true,
    },
    {
      title: '图片',
      dataIndex: 'img_url',
      key: 'img_url',
      align: 'center',
      render: (_, record) => <Avatar size={32} src={record.img_url} icon={<FundViewOutlined/>}/>,
      hideInSearch: true,
    },
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      align: 'center',
    },
    {
      title: '分类名称',
      dataIndex: 'category_name',
      key: 'category_name',
      hideInSearch: true,
    },
    {
      title: '点击量',
      dataIndex: 'hits',
      key: 'hits',
      hideInSearch: true,
    },
    {
      title: '排序',
      dataIndex: 'sort',
      key: 'sort',
      hideInSearch: true,
    },
    {
      title: '置顶',
      dataIndex: 'is_top',
      render: (_, record) => (
        <Switch
          checkedChildren="启用"
          unCheckedChildren="禁用"
          defaultChecked={record.is_top === 1}
          loading={record.content_id + 'top' === lockId}
          onChange={async () => handleIsContent(record, record.is_top, 'top')}
        />
      ),
      hideInSearch: true,
    },
    {
      title: '热门',
      dataIndex: 'is_hot',
      render: (_, record) => (
        <Switch
          checkedChildren="启用"
          unCheckedChildren="禁用"
          defaultChecked={record.is_hot === 1}
          loading={record.content_id + 'hot' === lockId}
          onChange={async () => handleIsContent(record, record.is_hot, 'hot')}
        />
      ),
      hideInSearch: true,
    },
    {
      title: '推荐',
      dataIndex: 'is_rec',
      render: (_, record) => (
        <Switch
          checkedChildren="启用"
          unCheckedChildren="禁用"
          defaultChecked={record.is_rec === 1}
          loading={record.content_id + 'rec' === lockId}
          onChange={async () => handleIsContent(record, record.is_rec, 'rec')}
        />
      ),
      hideInSearch: true,
    },
    {
      title: '是否隐藏',
      dataIndex: 'is_hide',
      render: (_, record) => (
        <Switch
          checkedChildren="启用"
          unCheckedChildren="禁用"
          defaultChecked={record.is_hide === 1}
          loading={record.content_id + 'hide' === lockId}
          onChange={async () => handleIsContent(record, record.is_hide, 'hide')}
        />
      ),
      hideInSearch: true,
    },
    {
      title: '添加时间',
      dataIndex: 'create_time',
      key: 'create_time',
      hideInSearch: true,
    },
    {
      title: '修改时间',
      dataIndex: 'update_time',
      key: 'update_time',
      hideInSearch: true,
    },
    {
      title: '操作',
      render: (_, record) => (
        <Space size="middle">
          <a onClick={() => isShowModal(true, record.content_id)}>编辑</a>
          <Popconfirm
            title="确定删除么？"
            onConfirm={() => {
              handleOk(record);
            }}
            okText="确定"
            cancelText="取消"
          >
            <a href={'javascript'}>删除</a>
          </Popconfirm>
        </Space>
      ),
      hideInSearch: true,
    },
  ];

  return (
    <PageContainer>
      <ProTable
        columns={columns}
        actionRef={actionRef}
        request={(params) => getData(params)}
        editable={{
          type: 'multiple',
        }}
        rowKey="content_id"
        dateFormatter="string"
        headerTitle="内容管理列表"
        toolBarRender={() => [
          <Button
            key="button"
            icon={<PlusOutlined/>}
            type="primary"
            onClick={() => isShowModal(true)}
          >
            新建
          </Button>,
          <Button
            key="button"
            icon={<DeleteOutlined/>}
            onClick={() => isShowRecycleModal(true)}
          >
            回收站
          </Button>,
        ]}
      />
      {!isModalVisible ? (
        ''
      ) : (
        <Edit
          isModalVisible={isModalVisible}
          isShowModal={isShowModal}
          actionRef={actionRef}
          editId={editId}
        />
      )}
      {!isModalRecycle ? (
        ''
      ) : (
        <Recycle
          isModalRecycle={isModalRecycle}
          isShowRecycleModal={isShowRecycleModal}
          actionRefIndex={actionRef}
        />
      )}
    </PageContainer>
  );
};

export default Index;
